package com.jxsa.exception;

import com.alibaba.fastjson.JSON;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author pwq
 */
@Component("customWebResponseExceptionTranslator")
public class CustomWebResponseExceptionTranslator implements WebResponseExceptionTranslator<OAuth2Exception> {
    @Override
    public ResponseEntity translate(Exception e) throws Exception {
        Map<String,Object> msg = new HashMap<>(3);
        msg.put("code",400);
        msg.put("data", StringUtils.isEmpty(e.getMessage())?"请求参数错误！":e.getMessage());
        if (e instanceof InvalidGrantException){
            msg.put("msg","凭据错误");
        }
        if (e instanceof InternalAuthenticationServiceException){
            msg.put("msg","用户名错误");
        }
        if (e instanceof UnsupportedGrantTypeException){
            msg.put("msg","错误的GrantType");
        }
        if (e instanceof InvalidTokenException){
            msg.put("msg","错误的凭据，请重新登录");
        }
        return handleOAuth2Exception(msg);
    }

    private ResponseEntity<String> handleOAuth2Exception(Map<String,Object> msg) throws IOException {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Cache-Control", "no-store");
        headers.set("Pragma", "no-cache");
        headers.set("Content-Type","application/json;charset=UTF-8");
        return new ResponseEntity<String>(JSON.toJSONString(msg), headers,
                HttpStatus.valueOf(401));
    }
}
